<script setup lang="ts">
import { columns, searchFormSchema } from './dept.data'
import { BasicTable, TableAction, useTable } from '@/components/Table'
import { deptApi } from '@/api/sys/deptApi'
import { IconEnum } from '@/enums/appEnum'
import { useModal } from '@/components/Modal'
import DeptModal from '@/views/sys/dept/DeptModal.vue'
import type { DeptDeleteReq } from '@/model/sys/deptModel'
import { removeEmptyChildren } from '@/utils/helper/treeHelper'
import { DeptComponentCodes } from '@/enums/componentCodesEnum'

defineOptions({ name: 'DeptList' })
const [registerModal, { openModal }] = useModal()
const [registerTable, { expandAll, collapseAll, reload }] = useTable({
  title: '部门列表',
  api: deptApi.tree,
  afterFetch(data) {
    removeEmptyChildren(data)
    return data
  },
  columns,
  rowKey: 'deptId',
  formConfig: { labelWidth: 120, schemas: searchFormSchema },
  isTreeTable: true,
  pagination: false,
  useSearchForm: true,
  showTableSetting: true,
  showIndexColumn: false,
  actionColumn: {
    width: 140,
    title: '操作',
    dataIndex: 'action',
    fixed: 'right',
  },
})

function handleAdd() {
  openModal(true, { isUpdate: false })
}

function handleUpdate(record: Recordable) {
  openModal(true, { record, isUpdate: true })
}

async function handleDelete(record: Recordable) {
  await deptApi.delete(record as DeptDeleteReq)
  reload()
}
</script>

<template>
  <div>
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button v-permission="DeptComponentCodes.Add" type="primary" :pre-icon="IconEnum.ADD" @click="handleAdd">
          新增
        </a-button>
        <a-button @click="expandAll">
          展开全部
        </a-button>
        <a-button @click="collapseAll">
          折叠全部
        </a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                icon: IconEnum.EDIT,
                label: '更新',
                permission: DeptComponentCodes.Update,
                onClick: handleUpdate.bind(null, record),
              },
              {
                icon: IconEnum.DELETE,
                danger: true,
                label: '删除',
                permission: DeptComponentCodes.Delete,
                popConfirm: {
                  title: '确定?',
                  placement: 'left',
                  confirm: handleDelete.bind(null, record),
                },
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <DeptModal @register="registerModal" @success="reload()" />
  </div>
</template>
